/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */


package org.amarena2d.examples.scenes.invader;

import com.android1.amarena2d.actions.base.Action;
import com.android1.amarena2d.actions.base.FunctionAction;
import com.android1.amarena2d.actions.base.RepeatForever;
import com.android1.amarena2d.actions.base.Sequence;
import com.android1.amarena2d.actions.movement.MoveBy;
import com.android1.amarena2d.commons.VoidFunction;
import com.android1.amarena2d.engine.collision.CollisionCallback;
import com.android1.amarena2d.nodes.Entity;
import com.android1.amarena2d.nodes.behavior.delegates.CollisionDelegate;
import com.android1.amarena2d.nodes.sprites.SharedSprite;
import com.badlogic.gdx.audio.Sound;

public class Shot extends SharedSprite {

    Entity owner;

    Sound shotsound;

    final VoidFunction lazyPlace = new VoidFunction() {
        @Override
        public void exec() {
            setXY(owner.getX() + 32 - 8, owner.getY() + 32 - 8);
        }
    };
    final Action fireAction = RepeatForever.$(Sequence.$(FunctionAction.$(lazyPlace), MoveBy.$(0, 300, 2)));

    public Shot() {
        super("invader/shot.png");
        setVisible(false);
    }

    @Override
    protected void onInit() {
        collision().setVolumeBox(3, 0, 5, 8)
                .setOnCollision(new CollisionCallback() {
                    @Override
                    public void on(CollisionDelegate self, CollisionDelegate target) {
                        doFireLoop();
                    }
                }).register();
    }

    public void start(Entity owner) {
        this.owner = owner;
        if (owner != null) {
            setVisible(true);
            doFireLoop();
        }
    }

    public void stopFireing() {
        action().stop(fireAction);
        setVisible(false);
    }

    private void doFireLoop() {
        action().run(fireAction);
    }

}